var todoMarkup;
var extendedTodoMarkup;
var iDAndDeadline;
var projectJSON;
var currentProject;
var userName;

$(function() {
  setUsersName();
  initProject();
  $('#filter').example('Search');
  $('#addProject').dialog({autoOpen: false, hide: "fadeOut", show: "blind",  draggable: true, modal: true, height: 130}, 'option', 'position', 'center');
});

function sortByTopic() {

}

function initProject() {
  if (!currentProject){
    currentProject = 'CASUAL';
  }

  iDAndDeadline = new Object();
  populateProjectSelection();
  renderTODOTable();
}

function clearProject() {
  $('#todoList').html('');
}

function populateProjectSelection() {
  $.post("home/getProjects", {username : username}, function(data) {
    var projects = data
    var options = '';
    for (var project in projects){
       options += '<option value="' + projects[project].projectName + '">' + projects[project].projectName + '</option>';
    }
    options += '<option value="' + 'new' + '">' + '-- ADD NEW --' + '</option>';
    $("#projectSelection").html(options);
  }, "json");
}

function changeProject(event) {
  clearProject();
  if ($(event.target).val() == "new") {
    addProject();
  }
  currentProject = $(event.target).val()
  initProject($(event.target).val());
}

function addProject() {
  $('#addProject').dialog('open');
}

function addBeautyTips() {
  $.each($('.beautyTip'), function(index, beautyTip) {
    var position = new Array();
    if ($(beautyTip).hasClass('rightTip')) {
      position.push('right');
    }
    if ($(beautyTip).hasClass('leftTip')) {
      position.push('left');
    }
    $(beautyTip).bt({
      fill: '#CDE69C',
      cssStyles: {color: '#638421', fontWeight: 'bold'},
      shrinkToFit: true,
      padding: 10,
      cornerRadius: 10,
      spikeLength: 15,
      spikeGirth: 5,
      positions: position
    });
  });
}

function quickCreateProject(event) {
  if (event.keyCode == '13') {
    createProject();
  }
  else {
    return;
  }
}

function createProject() {
  $('#addProject').dialog('close');
  var newProject = $("#projectName").val().trim().toUpperCase();
  $.post("home/createProject", {projectName : newProject, username : username}, function(){
    $('#projectSelection')[0].options[$('#projectSelection')[0].options.length - 1] = new Option(newProject, newProject);
    $('#projectSelection')[0].options[$('#projectSelection')[0].options.length] = new Option('-- ADD NEW --', 'new');
    $($('#projectSelection')[0]).val(newProject);
    currentProject = newProject;
    initProject();
  });
}

function cancelNewProject() {
  $('#addProject').dialog('close');
}

function setUsersName() {
  var cookieValue = $.url.decode(getCookie("myTodo"));
  if(cookieValue == "null") {
    document.location.href = "index.jsp";
  }
  cookieValue = cookieValue.substring(cookieValue.indexOf("{"));
  var user = new Object;
  user = $.parseJSON(cookieValue);
  username = user.userName;
//  $('.loggedInUser').html(user.name.toUpperCase() + " ");
}


function renderTODOTable() {
  var todoMarkup = $("#TODOTemplate").html();
  var extendedTodoMarkup = $("#TODOExtendedTemplate").html();
  <!--Compile markup strings as named templates-->
  $.template("todoTemplate", todoMarkup);
  $.template("todoExtendedTemplate", extendedTodoMarkup);
  $.post(
    "home/getProject", {projectName : currentProject, username: username}, //TODO: remove hardcoded username
    function(data){
      var assignments = data;
      for (var task in assignments) {
        iDAndDeadline[assignments[task].id] = assignments[task].deadline;
        $.tmpl("todoTemplate", assignments[task]).appendTo("#todoList");
        $.tmpl("todoExtendedTemplate", assignments[task]).appendTo("#todoList").hide();
        $('#' + assignments[task].id + '_extended').find('.stateSelection').val(assignments[task].status);
        $('#projectSelection').val(currentProject);
      }}, "json"
  ).success(function() {
                  postRender();
  });
}

function postRender() {
  addBeautyTips();
  convertPrioritiesToImage();
  generatePriorityPickers();
  generateTags();
  populateTODOCounts();
  bindStatusHandlers();
  $.each($('.tagHolder'), function(index, value) {
    $($('.tagHolder')[index]).tagsInput()
  });
}

function bindStatusHandlers() {
  $.each($('.START'), function(index, startButton) {
    $(startButton).click(function() {
      $.post("home/changeState", {id: $(startButton).parent().parent().attr("id"), state: 'FINISH'}, function(data){
        startTask(startButton);
      }, "json");
    });
  });
  $.each($('.FINISH'), function(index, startButton) {
    $(startButton).click(function() {
      $.post("home/changeState", {id: $(startButton).parent().parent().attr("id"), state: 'DONE'}, function(data){
        finishTask(startButton);
      }, "json");
    });
  });
}

function restartTask(button) {
  $(button).removeClass('DONE').removeClass('FINISH').addClass('START');
  $(button).val('START');
  $(button).click(function() {
    startTask(button)
  });
}

function startTask(button) {
  $(button).removeClass('START').removeClass('DONE').addClass('FINISH');
  $(button).val('FINISH');
  $(button).click(function() {
    finishTask(button)
  });
}

function finishTask(button) {
  $(button).removeClass('FINISH').removeClass('START').addClass('DONE');
  $(button).val('DONE');
}

function populateTODOCounts() {
  var TODOsToday = 0;
  var TODOsArchived = 0;
  var TODOsThisWeek = 0;
  var today = new Date();
  var day = (today.getDate().length == 1 ? ("0" + today.getDate()) : today.getDate());
  var month = ((today.getMonth() + 1 + "").length == 1 ? ("0" + (today.getMonth() + 1)) : (today.getMonth() + 1));
  var todayFormatted = day + "/" + month + "/" + today.getFullYear();
  $.each(iDAndDeadline, function(index, deadLine) {
    if (deadLine == todayFormatted) {
      TODOsToday ++;
    }
  });
  $('#TODOsToday').html(TODOsToday);
}

function addNew() {
  $.post("home/newTodo", {projectName : currentProject, username: username}, function(data){
    var id = data;
    var assignment = new Object();
    assignment['id'] = "" + id;
    assignment['status'] = "START";
    assignment['priority'] = '1';
    $.tmpl("todoExtendedTemplate", assignment).prependTo("#todoList").hide();
    $.tmpl("todoTemplate", assignment).prependTo("#todoList");
    $("#" + id).find(".id").click();
    convertPriorityToImage({"value" : $("#" + id).find(".collapsed-priority")});
    generatePriorityPicker($("#" + id + "_extended").find('.priorityPicker')[0]);
    $($('.tagHolder')[0]).tagsInput();
    var startButton = $("#" + id).find('.START');
    $(startButton).click(function() {
      startTask(startButton)
    });
  }, "json")
}

function convertPrioritiesToImage() {
  $.each($('.collapsed-priority'), function(index, value) {
    convertPriorityToImage({"value" : value});
  });
}

function convertPriorityToImage(event) {
  var barHolder = $(event.value).find('.bars');
  var bars = parseInt($(event.value).find('.priorityNumber').val());
  barHolder.html('');
  for (var i = 1; i <= bars; i++) {
    $($(event.value).find('.bars').append("<img class='" + i + "'src='images/bar.png'/> "));
  }
}

function generatePriorityPickers() {
  var priorityContainers = $('.priorityPicker');
  $.each(priorityContainers, function(index, value) {
    generatePriorityPicker(value);
  });
}

function generatePriorityPicker(value) {
  var bars = parseInt($(value).find('.priorityNumber').val());
  for (var i = 1; i <= bars; i++) {
    $(value).find('.bars').append("<img class='" + i + "'src='images/bar.png' onmouseover='highlightPreviousBars(event)' onmouseout='restoreBars(event)' onclick='setBars(event)'/> ");
  }
  for (var i = bars + 1; i <= 5; i++) {
    $(value).find('.bars').append("<img class='" + i + "'src='images/bar-light.png' onmouseover='highlightPreviousBars(event)' onmouseout='restoreBars(event)' onclick='setBars(event)'/> ");
  }
}

function generateTags() {
  $.each($('.tags'), function(index, tagCSVHolder) {
    formatTags(tagCSVHolder);
  });
}

function formatTags(tagCSVHolder) {
  var tags = $(tagCSVHolder).html().split(",");
  $(tagCSVHolder).html('');
  if (tags.length < 1 || (tags.length == 1 && tags[0] == '')) {
    return
  }
  $.each(tags, function(index, tag) {
    $(tagCSVHolder).append("<span class='tags-topic'>" + tag + "</span>");
  });
}

function highlightPreviousBars(event) {
  var targetBar = $(event.target);
  var barNumber = parseInt(targetBar.attr("class"));
  var barHolder = targetBar.parent();
  for (var i = 1; i <= barNumber; i++) {
    barHolder.find('.' + i).attr("src", "images/bar.png");
  }
  for (var i = barNumber + 1; i <= 5; i++) {
    barHolder.find('.' + i).attr("src", "images/bar-light.png");
    ;
  }
}

function restoreBars(event) {
  var targetBar = $(event.target);
  var barHolder = targetBar.parent();
  var bars = barHolder.parent().find('.priorityNumber').val();
  for (var i = 1; i <= 5; i++) {
    barHolder.find('.' + i).attr("src", "images/bar-light.png");
  }
  for (var i = 1; i <= bars; i++) {
    barHolder.find('.' + i).attr("src", "images/bar.png");
  }
  ;
}

function setBars(event) {
  var clickedBar = $(event.target);
  clickedBar.parent().parent().find('.priorityNumber').val(clickedBar.attr("class"));
}

function expandTODO(id) {
  $("#" + id).hide();
  $("#" + id + "_extended").show();
  $("#" + id + "_deadline").datepicker({constrainInput: false, minDate: new Date});
  $('#' + id + "_extended").find('.stateSelection').val($('#' + id).find('.statusButton').val());
}

function unExpandTODO(id) {
  $("#" + id + "_extended").hide();
  $("#" + id).show();
}

function unExpandAndSaveTODO(id) {
  var extendedRow = $("#" + id + "_extended");
  var newTopic = extendedRow.find(".topic").val();
  var newState = extendedRow.find('.stateSelection').val();
  var newDeadline = extendedRow.find("#" + id + "_deadline").val();
  var newPriority = extendedRow.find(".priorityNumber").val();
  var newTags = extendedRow.find(".tagHolder").val();
  var newComments = extendedRow.find(".comments").val();

  if (extendedRow.find(".topic").val().trim() == '') {
    $('#todoTable').find(extendedRow).remove();
    $('#todoTable').find($('#' + id)).remove();
    return;
  }
  $.post("home/saveTodo", {priority : newPriority, topic : newTopic, state : newState, deadLine : newDeadline, tags : newTags, comments : newComments, id : id},
    function(data){
      unExpandTODO(id);
      if (newState == 'DONE') {
        finishTask($("#" + id).find('.statusButton'));
      }
      if (newState == 'FINISH') {
        startTask($("#" + id).find('.statusButton'));
      }
      if (newState == 'START') {
        restartTask($("#" + id).find('.statusButton'));
      }
      var collapsedRow = $("#" + id);
      collapsedRow.find(".topic").html(newTopic);
      collapsedRow.find(".deadline").html(newDeadline);
      collapsedRow.find(".priorityNumber").val(newPriority);
      collapsedRow.find(".tags").html(newTags);
      formatTags(collapsedRow.find(".tags"));
      convertPriorityToImage({"value" : $("#" + id).find(".collapsed-priority")});
      convertPriorityToImage({"value" : $("#" + id).find(".collapsed-priority")});
      iDAndDeadline[id] = newDeadline;
      populateTODOCounts();
    }, "json");
}

function deleteTODO(target) {
  $.post("home/deleteTodo", {id : target}, function() {
    iDAndDeadline[target] = '';
    $('#' + target).remove();
    $('#' + target + "_extended").remove();
    populateProjectSelection();
    initProject();
    populateTODOCounts();
  }, "json")
}

function quickSearch(e) {
  if (e.keyCode == 13) {
    search();
  }
  else {
    return false;
  }
}

function search() {
  var defaultValue = "search";
  var filter = $('#filter').val().toLowerCase().trim();
  if (filter == defaultValue) {
    filter = '';
  }
  var filteredIds = [];
  var fieldsToSearchFrom = ['id', 'topic', 'deadline', 'comment', 'tags', 'status'];
  if (filter.indexOf(":") != -1) {
    fieldsToSearchFrom = getAdvancedSearchField(fieldsToSearchFrom, filter);
    filter = filter.substr(filter.indexOf(":") + 1).trim();
  }
  $.getJSON(projectJSON,
    function(assignments) {
      for (var task in assignments) {
        var assignment = assignments[task];
        $.each(fieldsToSearchFrom, function(index, parameterName) {
          if ((assignment[parameterName]).toLowerCase().indexOf(filter) != -1) {
            filteredIds.push(assignment['id']);
          }
        })
      }
    }).success(function() {
    showFilteredTODOs(filteredIds);
  });

}

function getAdvancedSearchField(allFields, filter) {
  var searchFields = [];
  $.each(allFields, function(index, field) {
    if (filter.indexOf(field + ":") != -1 || filter.indexOf(field + " :") != -1) {
      searchFields.push(field);
    }
  });
  return (searchFields.length == 1) ? searchFields : allFields;
}

function showFilteredTODOs(filteredIds) {
  hideAllTODOs();
  $.each(filteredIds, function(index, id) {
    $("#" + id).show();
  })
}

function hideAllTODOs() {
  $.each($('.extended-TODO'), function(index, value) {
    $($('.collapsed-TODO')[index]).hide();
  })
  $.each($('.extended-TODO'), function(index, value) {
    $($('.extended-TODO')[index]).hide();
  })
}

function logout(){
  document.cookie = "myTodo=null";
  document.location.href = "index.jsp";
}

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-30653074-1']);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script');
  ga.type = 'text/javascript';
  ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(ga, s);
})();